<?php defined('SYSPATH') or die('No direct script access.');

/**
 *
 * @package Popo
 */
class Jefri_Entity_Writer_Json extends Jefri_Entity_Writer {
	public function new_entity_writer($obj) {
		return new Jefri_Entity_Writer_Entity_Json($obj);
	}

	public function to_string() {
		$entities = array();
		foreach($this->entities as $ent)
		{
			$entities[] = $ent->to_array();
		}

		$transaction = array(
			"meta"     => $this->meta,
			"entities" => $entities,
		);

		return json_encode($transaction);
	}

	public static function json_clean($text) {
#		$text = preg_replace("/\n/s", '', $text);
#		$text = preg_replace("/\s+/s", ' ', $text);
		$text = preg_replace('/,?\s*([\}\]])/', '\1', $text);
#		$text = str_replace(chr(10), "", $text);
#		$text = str_replace(chr(13), "", $text);
#		$text = str_replace("\n", "", $text);
#		$text = str_replace("\t", "", $text);
#		$text = preg_replace('/\s*([\[\{\}\]])\s*/', '\1', $text);
#		$text = preg_replace('/([,:])\s*"/', '\1"', $text);
		return $text;
	}
}

class Jefri_Entity_Writer_Entity_Json extends Jefri_Entity_Writer_Entity {
	public function to_string(){
		return json_encode($this->to_array());
	}

	public function to_array(){
		$entity_array = array(
			"_type" => $this->type,
			"uuid"  => $this->id,
		);
		foreach($this->properties as $prop => $val)
		{
			$entity_array[$prop] = $val;
		}
		return $entity_array;
	}
}
